package hxtc.browser;

/**
 * ...
 * @author Cref
 */
import hxtc.dom.Control;
import haxe.macro.Expr;
import haxe.macro.Context;
#if !macro
import jstm.Host;
#end

class Embedding {

	@:macro public static function register(e:ExprRequire<Class<Control>>, embedId:String):Expr {
		return Context.parse('untyped hxtc.browser.Embedding.embedClasses.set("'+embedId+'","'+jstm.MacroTest._getTypeName(e)+'")',e.pos);
	}
	#if !macro
	static var embedClasses:Hash<String>;
	static var embeds:Hash<HTMLElement>;
	//static var embedSelector = new hxtc.dom.style.Selector('embed');//TODO: descendants of controlling control
	
	static function __init__() {
		embeds = new Hash();
		embedClasses = new Hash();
	}
	
	//checks the document for new embed elements
	public static function refresh() {
		var placeholders = Host.window.document.body.getElementsByTagName('embed');
		for (e in placeholders) {
			if (!embedClasses.exists(e.id)) continue;
			if (embeds.exists(e.id)) embeds.get(e.id).swap(e);//TODO: e.ctrl.draw(), later weer baseren op config op basis van css
			else {
				e.style.display = 'none';
				jstm.Runtime.useClass(embedClasses.get(e.id), function(C:Class<hxtc.dom.UIControl<Dynamic>>) {
					var ctrl:hxtc.dom.UIControl<Dynamic> = untyped __new__(C);
					var ce:HTMLElement = Host.window.document.createElement(ctrl.tagName);
					ce.id = e.id;
					//TODO: clasName should be set here as well
					embeds.set(ce.id,ce);
					ctrl.bind(cast ce.swap(e));
				});
			}
			//var c = doc.buildElement({div:['zoekie!'],style:'border:2px solid green'}).swap(e);
			//if (ctrl.id != '') lookupIdInConfig();
			//var cn = ctrl.className.split(' ')[1];
			//ctrl.innerText = ctrl.id == ''?cn:ctrl.id;//Reflect.field(getConfig(), ctrl.id)._;
			//ctrl.className = cn;
		}
	}
	#end
	
}